package com.atguigu.tingshu.payment.service.impl;

import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.atguigu.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WxPayServiceImpl implements WxPayService {

	@Autowired
	private PaymentInfoService paymentInfoService;

	@Autowired
	private WxPayV3Config wxPayV3Config;

	@Autowired
	private RSAAutoCertificateConfig rsaAutoCertificateConfig;


	@Override
	public Map<String, Object> createJsapi(String paymentType, String orderNo, Long userId) {

		// 1.保存交易信息
		PaymentInfo paymentInfo = paymentInfoService.savePaymentInfo(paymentType,orderNo,userId);

		//2.调用微信SDK获取小程序支付所需参数
		//2.1 构建调用微信接口业务对象
		JsapiServiceExtension jsapiService = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();
		//2.2 构建预支付请求对象
		PrepayRequest prepayRequest = new PrepayRequest();
		Amount amount = new Amount();
		//2.2.1 设置预支付订单金额 单位：分 TODO开发接口暂时硬编码1分 实际应该从paymentInfo对象中获取
		amount.setTotal(1);
		prepayRequest.setAmount(amount);
		prepayRequest.setAppid(wxPayV3Config.getAppid());
		prepayRequest.setMchid(wxPayV3Config.getMerchantId());
		prepayRequest.setDescription(paymentInfo.getContent());
		prepayRequest.setNotifyUrl(wxPayV3Config.getNotifyUrl());
		//2.3 TODO 目前小程序未发布，开发阶段必选设置付款人（真正付款只有应用开发者列表中微信账户才有权限）
		Payer payer = new Payer();
		payer.setOpenid("oupd_6BVdcZFDki5DQ1WLhnSKorI");//TODO同学改为自己微信账户OpenID 能拉起微信支付，但是付款会报错：当前用户不是开发者
		prepayRequest.setPayer(payer);
		//2.2.2 商户端订单编号
		prepayRequest.setOutTradeNo(paymentInfo.getOrderNo());
		//2.3 调用下单方法（小程序所需参数），得到应答
		PrepayWithRequestPaymentResponse response = jsapiService.prepayWithRequestPayment(prepayRequest);
		if (response != null) {
			Map<String, Object> mapResult = new HashMap<>();
			mapResult.put("timeStamp", response.getTimeStamp());
			mapResult.put("package", response.getPackageVal());
			mapResult.put("paySign", response.getPaySign());
			mapResult.put("signType", response.getSignType());
			mapResult.put("nonceStr", response.getNonceStr());
			return mapResult;
		}
		return null;
	}
}
